Explain how to pass an array to a function in GoLang | Go Programming Language
In this article, you will learn how to pass an array to a function in Go Programming Language
Arrays in GoLang are similar to other existing programming Languages. In the Program, the programmer looks for a data type that can store multiple values of the same data type for that array data type. An array is a fixed length data type which is used to store homogeneous elements in the memory. Due to the fixed length feature, they are not quite as popular in teh GoLang language as slice. In an array, the user is allowed to store zero or can store more than zero elements in it. The elements of the array are called by using the index. The index of the array starts with 0 and ends with the size-1. In Go language, the user is allowed to pass an array as an argument in the function. For passing an array as an argument in the function, the user has to initially create a formal parameter through the following syntax.
Syntax:
// For sized array
func function_name(nameofvariable [size] Type) {
// set of statements
}
Using this syntax, the user can pass D1 or multiple dimensional arrays to the function.
Example:
package mainimport "fmt"// This function acceptan array as an argumentfunc myfun(a [6]int, size int) int { var i, element, r int for j = 0; j < size; j++ { element += a[j] } r = element / size return r}// Main functionfunc main() { // Creating and initializing an array var ar = [6]int{23, 82, 20, 5, 40, 34} var res int // Passing an array as an argument res = myfun(ar, 6) fmt.Printf("Final result is: %d ", res)}Output:
Final result is: 34


